"""
VPN客户端主程序 - PyQt5界面
"""
import sys
import os
from PyQt5.QtWidgets import (QApplication, QMainWindow, QWidget, QVBoxLayout,
                             QHBoxLayout, QLabel, QLineEdit, QPushButton,
                             QSystemTrayIcon, QMenu, QMessageBox, QCheckBox)
from PyQt5.QtCore import Qt, QTimer
from PyQt5.QtGui import QIcon
from client_socket import ClientSocket


class VPNClientWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.client_socket = ClientSocket()
        self.tray_icon = None
        self.init_ui()
        self.init_tray()

    def init_ui(self):
        """初始化界面"""
        self.setWindowTitle("VPN客户端")
        self.setGeometry(100, 100, 400, 300)
        
        # 设置窗口图标
        if os.path.exists('icon.png'):
            self.setWindowIcon(QIcon('icon.png'))
        
        # 主窗口部件
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        layout = QVBoxLayout()
        central_widget.setLayout(layout)
        
        # 标题
        title = QLabel("VPN客户端")
        title.setAlignment(Qt.AlignCenter)
        title.setStyleSheet("font-size: 20px; font-weight: bold; margin: 20px;")
        layout.addWidget(title)
        
        # 用户名输入
        username_layout = QHBoxLayout()
        username_label = QLabel("用户名:")
        username_label.setFixedWidth(80)
        self.username_input = QLineEdit()
        self.username_input.setPlaceholderText("请输入用户名")
        username_layout.addWidget(username_label)
        username_layout.addWidget(self.username_input)
        layout.addLayout(username_layout)
        
        # 密码输入
        password_layout = QHBoxLayout()
        password_label = QLabel("密码:")
        password_label.setFixedWidth(80)
        self.password_input = QLineEdit()
        self.password_input.setPlaceholderText("请输入密码")
        self.password_input.setEchoMode(QLineEdit.Password)
        password_layout.addWidget(password_label)
        password_layout.addWidget(self.password_input)
        layout.addLayout(password_layout)
        
        # 保持登录选项
        self.keep_login_checkbox = QCheckBox("保持登录")
        layout.addWidget(self.keep_login_checkbox)
        
        # 登录按钮
        self.login_button = QPushButton("登录")
        self.login_button.setStyleSheet("""
            QPushButton {
                background-color: #4CAF50;
                color: white;
                padding: 10px;
                border-radius: 5px;
                font-size: 14px;
            }
            QPushButton:hover {
                background-color: #45a049;
            }
        """)
        self.login_button.clicked.connect(self.login)
        layout.addWidget(self.login_button)
        
        # 状态标签
        self.status_label = QLabel("未连接")
        self.status_label.setAlignment(Qt.AlignCenter)
        self.status_label.setStyleSheet("color: gray; margin: 10px;")
        layout.addWidget(self.status_label)
        
        # 断开按钮（初始隐藏）
        self.disconnect_button = QPushButton("断开连接")
        self.disconnect_button.setStyleSheet("""
            QPushButton {
                background-color: #f44336;
                color: white;
                padding: 10px;
                border-radius: 5px;
                font-size: 14px;
            }
            QPushButton:hover {
                background-color: #da190b;
            }
        """)
        self.disconnect_button.clicked.connect(self.disconnect)
        self.disconnect_button.setVisible(False)
        layout.addWidget(self.disconnect_button)
        
        layout.addStretch()

    def init_tray(self):
        """初始化系统托盘"""
        if not QSystemTrayIcon.isSystemTrayAvailable():
            QMessageBox.critical(self, "系统托盘", "系统不支持系统托盘")
            return
        
        # 创建托盘图标
        icon_path = 'icon.png' if os.path.exists('icon.png') else None
        if icon_path:
            self.tray_icon = QSystemTrayIcon(QIcon(icon_path), self)
        else:
            self.tray_icon = QSystemTrayIcon(self)
        
        # 创建托盘菜单
        tray_menu = QMenu()
        
        show_action = tray_menu.addAction("显示窗口")
        show_action.triggered.connect(self.show)
        
        quit_action = tray_menu.addAction("退出")
        quit_action.triggered.connect(self.quit_application)
        
        self.tray_icon.setContextMenu(tray_menu)
        self.tray_icon.activated.connect(self.tray_icon_activated)
        self.tray_icon.show()
        
        # 设置提示
        self.tray_icon.setToolTip("VPN客户端")

    def tray_icon_activated(self, reason):
        """托盘图标激活事件"""
        if reason == QSystemTrayIcon.DoubleClick:
            self.show()
            self.raise_()
            self.activateWindow()

    def login(self):
        """登录"""
        username = self.username_input.text().strip()
        password = self.password_input.text().strip()
        
        if not username or not password:
            QMessageBox.warning(self, "警告", "请输入用户名和密码")
            return
        
        self.login_button.setEnabled(False)
        self.status_label.setText("正在连接...")
        self.status_label.setStyleSheet("color: orange; margin: 10px;")
        
        def login_callback(success, message):
            if success:
                self.status_label.setText("已连接")
                self.status_label.setStyleSheet("color: green; margin: 10px;")
                self.login_button.setVisible(False)
                self.disconnect_button.setVisible(True)
                self.username_input.setEnabled(False)
                self.password_input.setEnabled(False)
                
                if self.tray_icon:
                    self.tray_icon.showMessage("VPN客户端", "连接成功", QSystemTrayIcon.Information, 2000)
                
                # 如果勾选了保持登录，可以保存凭据（实际应用中应该加密）
                if self.keep_login_checkbox.isChecked():
                    # 这里可以保存登录信息
                    pass
            else:
                self.status_label.setText("连接失败")
                self.status_label.setStyleSheet("color: red; margin: 10px;")
                QMessageBox.warning(self, "登录失败", message)
                self.login_button.setEnabled(True)
        
        # 在新线程中连接
        import threading
        thread = threading.Thread(
            target=self.client_socket.connect,
            args=(username, password, login_callback)
        )
        thread.daemon = True
        thread.start()

    def disconnect(self):
        """断开连接"""
        self.client_socket.disconnect()
        self.status_label.setText("未连接")
        self.status_label.setStyleSheet("color: gray; margin: 10px;")
        self.login_button.setVisible(True)
        self.login_button.setEnabled(True)
        self.disconnect_button.setVisible(False)
        self.username_input.setEnabled(True)
        self.password_input.setEnabled(True)
        
        if self.tray_icon:
            self.tray_icon.showMessage("VPN客户端", "已断开连接", QSystemTrayIcon.Information, 2000)

    def closeEvent(self, event):
        """关闭事件"""
        if self.tray_icon and self.tray_icon.isVisible():
            QMessageBox.information(self, "提示", "程序将继续在系统托盘中运行")
            self.hide()
            event.ignore()
        else:
            self.quit_application()

    def quit_application(self):
        """退出应用程序"""
        self.client_socket.disconnect()
        if self.tray_icon:
            self.tray_icon.hide()
        QApplication.quit()

    def show(self):
        """显示窗口"""
        super().show()
        self.raise_()
        self.activateWindow()


def main():
    app = QApplication(sys.argv)
    app.setQuitOnLastWindowClosed(False)  # 允许在关闭窗口后继续运行
    
    window = VPNClientWindow()
    window.show()
    
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()

